package signGrammar.expressions;

import static signGrammar.expressions.util.CExpressionElement._;

import java.util.LinkedHashMap;
import java.util.Map;

import signGrammar.IShape;
import signGrammar.expressions.util.CExpressionElement;
import signGrammar.expressions.util.CExpressionElementArrayBuilder;

public class CVariable implements IGrammarExpression{
	private static Map<String, Integer> variables = new LinkedHashMap<String, Integer>();
	
	private static String makeVariableName(String type, Integer id){
		return type + "_" + id;
	}
	
	private static Integer incTypeInstance(String type){
		Integer count = variables.get(type) + 1;
		variables.put(type, count);
		return count;
	}
	
	public static CVariable create(String typeSign){
		String type = typeSign.split("_")[0];
		
		if( !variables.containsKey( type ) )
			variables.put(type, -1);
		
		return new CVariable(
				makeVariableName(type, incTypeInstance(type)),
				type);
	}

	private String variableName;
	private String representation;

	private CVariable(String variableName, String representation) {
		this.variableName = variableName;
		this.representation = representation;
	}

	@Override
	public IShape evaluate(IGrammarContext context) {
		return context.find(variableName);
	}

	@Override
	public IGrammarExpression replace(String name, IGrammarExpression expression) {
		if( variableName.equals( name ) )
			return expression.clone();
		return clone();
	}

	@Override
	public IGrammarExpression clone(){
		return create(variableName);
	}
	
	@Override
	public String toString(){
		return representation;
	}

	@Override
	public CExpressionElement[] toElements() {
		return new CExpressionElementArrayBuilder()
			.add( _(variableName) )
			.get();
	}
}
